package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.RuleDetailMapper;
import com.indusfo.spc.mapper.RuleMapper;
import com.indusfo.spc.mapper.RuleWatercodeMapper;
import com.indusfo.spc.pojo.Rule;
import com.indusfo.spc.pojo.RuleDetail;
import com.indusfo.spc.pojo.RuleWatercode;
import com.indusfo.spc.service.RuleService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Service("ruleService")
public class RuleServiceImpl implements RuleService {

    private  static  final Logger logger = LoggerFactory.getLogger(RuleServiceImpl.class);

    @Resource
    private RuleMapper ruleMapper;

    @Resource
    private RuleDetailMapper ruleDetailMapper;
    @Resource
    private RuleWatercodeMapper ruleWatercodeMapper;
    //查询
    @Override
    public JSONObject queryRule(Rule rule) {
        try {
            //获取页面的数据个数
            Integer pagesize = rule.getPagesize();
            //获取查询的页数
            Integer pageindex = rule.getPageindex();
            if(pagesize!=null && pageindex !=null){
                rule.setIncept(pagesize*(pageindex-1));
            }
            //执行查询操作
            List<Rule> ruleList=ruleMapper.queryRule(rule);

            //如果页数和页面数量都不为空的情况下进行计数
            if(ruleList.isEmpty()){
                return  JSONObject.oK(HintMessage.QUERY_NULL,ruleList,0);
            }else{
                Integer count= ruleMapper.countRule(rule);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS,ruleList,count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }
    }

    /**
     * @Author 熊冰 //新增
     * @Date 2020/1/16 14:32
     */
    @Override
    public JSONObject insertRule(Rule rule) {
        try{
            if(rule.getRuleId()!=null){
                throw new ModifyFailedException(HintMessage.INSERT_ID);
            }
            //初始化基础数据
            if(rule.getDataState()==null){
                rule.setDataState(1);
            }
            //判重
            checkParam(rule);
            //执行新增操作
            Integer row=ruleMapper.insertRule(rule);
            if(row==0){
                throw new ModifyFailedException(HintMessage.INSERT_DEFEATED);
            }
            return JSONObject.oK(HintMessage.INSERT_SUCCESS);
        }catch(GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    //修改
    @Override
    public JSONObject updateRule(Rule rule) {
        try {
            if(rule.getRuleId()==null) {
                throw new ParamsErrorException(HintMessage.UPDATE_ID);
            }
            //初始化基础数据
            if(rule.getDataState()==null){
                rule.setDataState(1);
            }
            //判重
            checkParam(rule);
            //执行修改操作
            int row = ruleMapper.updateRule(rule);
            if(row == 0) {
                throw new ModifyFailedException(HintMessage.UPDATE_DEFEATED);
            }
            return JSONObject.oK(HintMessage.UPDATE_SUCCESS);
        }catch (GlobalException e) {//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    //删除
    @Override
    public JSONObject deleteRule(Integer[] ruleIds, Integer dataState) {
        try{
            //空值判断
            if(dataState == null) {
                throw new ParamsErrorException(HintMessage.DATASTATE_NULL);
            }
            if(ruleIds == null) {
                throw new ParamsErrorException(HintMessage.LIST_NULL);
            }
            //记录异常信息
            String msg = "";
            switch (dataState) {
                case 1:
                    msg = HintMessage.START_VALUE;break;
                case 2:
                    msg = HintMessage.DELETE_VALUE;break;
                case 3:
                    msg = HintMessage.STOP_VALUE;break;
                default:
                    throw new ParamsErrorException(HintMessage.VIOLATION_OPERATION);
            }
            // 判断物料是否使用条码规则
            int rows = ruleMapper.selectMat(ruleIds);
            if(rows > 0){
                throw new ParamsErrorException(HintMessage.MAT_USE+","+HintMessage.DELETE_DEFEATED);
            }
            //执行删除操作
            int row = ruleMapper.deleteRule(ruleIds,dataState);
            //声明msg字符串，用来存抛出的异常
            if (row == 0) {
                msg=msg+ HintMessage.DEFEATED_VALUE;
            } else {
                msg=msg+ HintMessage.SUCCESS_VALUE;
            }
            return JSONObject.oK(msg);
        }catch(GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    /**
     * @Author 熊冰 通用的
     * @Date 2020/1/17 13:56
     */
    @Override
    public  List<String>  otherRule(Integer ruleId,Integer createNum){
        Rule rule=new Rule();
        rule.setRuleId(ruleId);
        rule.setCreateNum(createNum);
        return   generateRule(rule);
    }
    /**
     * @Author 熊冰  任务单用的
     * @Date 2020/1/17 13:55
     */
    @Override
    public  List<String>  orderRule(Integer matId,Integer createNum){
        Rule rule=new Rule();
        rule.setMatId(matId);
        rule.setCreateNum(createNum);
        return   generateRule(rule);
    }
    /**
     * @Author 熊冰  批次使用的
     * @Date 2020/1/17 13:54
     */
    @Override
    public  List<String>  batchRule(Integer orderId,Integer createNum){
        Rule rule=new Rule();
        rule.setOrderId(orderId);
        rule.setCreateNum(createNum);
        return   generateRule(rule);
    }
    @Override
    public  List<String>  generateRule(Rule rule) {
        if(rule==null){
            throw new ParamsErrorException(HintMessage.DATA_NULL);
        }
        Integer ruleId=rule.getRuleId();
        Integer orderId=rule.getOrderId();
        Integer matId=rule.getMatId();
        if(orderId!=null){
            if(ruleId==null) {
                ruleId = ruleMapper.queryRuleIdByOrderId(orderId);
            }
            matId=ruleMapper.queryMatIdByOrderId(orderId);
        }
        if(matId!=null){
            if(ruleId==null) {
                ruleId = ruleMapper.queryRuleIdByMatId(matId);
            }
        }
        if(ruleId==null){
            throw new ParamsErrorException(HintMessage.RULEID_NULL);
        }
        int cout=0;
        //判断是条码规则是否符合规范
        List<RuleDetail> ruleDetails = ruleDetailMapper.queryRuleDetailByRuleId(ruleId);
        if(ruleDetails==null){
            throw new ParamsErrorException(HintMessage.RULEDETALI_NULL);
        }
        //将值放入备注
        //静态数据
        String staticValue="";
        //数值初始值
        Integer numValue=null;
        Integer numLength=null;
        Integer numStep=null;
        Integer createNum=rule.getCreateNum();
        if(createNum==null){
            createNum=1;
        }

        for (RuleDetail ruleDetail :ruleDetails) {
            //数值
            if(ruleDetail.getRuleTypeId()==1){
                cout=cout+1;
                if(ruleDetail.getNumValue()==null){
                    throw new ParamsErrorException(HintMessage.NUMVALUE_NULL);
                }
                if(1>ruleDetail.getNumLength()){
                    throw new ParamsErrorException(HintMessage.NUMLENGTH_SMALL);
                }
                if(Math.pow(10, ruleDetail.getNumLength())<ruleDetail.getNumStep()){
                    throw new ParamsErrorException(HintMessage.NUMLENGTH_NUMSTEP);
                }
                numValue=ruleDetail.getNumValue();
                numLength=ruleDetail.getNumLength();
                numStep=ruleDetail.getNumStep();

            }
            //日期
            if(ruleDetail.getRuleTypeId()==2){
                SimpleDateFormat df = null;
                switch (ruleDetail.getRuleFormatId()) {
                    case 1:
                        df = new SimpleDateFormat("YYYY");
                        break;
                    case 2:
                        df = new SimpleDateFormat("YY");
                        break;
                    case 3:
                        df = new SimpleDateFormat("MM");
                        break;
                    case 4:
                        df = new SimpleDateFormat("dd");
                        break;
                    case 5:
                        df = new SimpleDateFormat("E", Locale.ENGLISH);
                        break;
                    default:
                        df = new SimpleDateFormat("YYYY");
                        break;
                }

                ruleDetail.setRemark(df.format(new Date()));

            }
            //常量
            if(ruleDetail.getRuleTypeId()==3){
                if(StringUtils.isEmpty(ruleDetail.getCharValue())){
                    throw new ParamsErrorException(HintMessage.CHARVALUE_NULL);
                }
                ruleDetail.setRemark(ruleDetail.getCharValue());

            }
            //变量
            if(ruleDetail.getRuleTypeId()==4){
                String date = "";
                if(ruleDetail.getVariateTypeId()==null){
                    throw new ParamsErrorException(HintMessage.VARIATETYPEID_NULL);
                }

                switch (ruleDetail.getVariateTypeId()) {
                    case 1:
                        if(matId==null){
                            throw new ParamsErrorException(HintMessage.MATID_NULL);
                        }
                        if(ruleDetail.getVariateFormatId()==null){
                            throw new ParamsErrorException(HintMessage.VARIATEFORMATID_NULL);
                        }
                        String  matCode=ruleMapper.queryMatCodeByMatId(matId);


                        ruleDetail.setRemark(cuttingOut(ruleDetail,matCode));
                        break;
                    case 2:
                        if(orderId==null){
                            throw new ParamsErrorException(HintMessage.ORDERID_NULL);
                        }
                        if(ruleDetail.getVariateFormatId()==null){
                            throw new ParamsErrorException(HintMessage.VARIATEFORMATID_NULL);
                        }
                        String orderNo=ruleMapper.queryOrderNoByOrderId(orderId);
                        ruleDetail.setRemark(cuttingOut(ruleDetail,orderNo));
                        break;
                    case 3:
                        if(matId==null){
                            throw new ParamsErrorException(HintMessage.MATID_NULL);
                        }
                        if(ruleDetail.getVariateFormatId()==null){
                            throw new ParamsErrorException(HintMessage.VARIATEFORMATID_NULL);
                        }
                        String  matModel=ruleMapper.queryMatModelByMatId(matId);

                        ruleDetail.setRemark(cuttingOut(ruleDetail,matModel));
                        break;
                    case 4:
                        if(orderId==null){
                            throw new ParamsErrorException(HintMessage.ORDERID_NULL);
                        }
                        if(ruleDetail.getVariateFormatId()==null){
                            throw new ParamsErrorException(HintMessage.VARIATEFORMATID_NULL);
                        }
                        String workShopCode=ruleMapper.queryWorkShopCodeByOrderId(orderId);
                        ruleDetail.setRemark(cuttingOut(ruleDetail,workShopCode));
                        break;
                    case 5:
                        if(orderId==null){
                            throw new ParamsErrorException(HintMessage.ORDERID_NULL);
                        }
                        if(ruleDetail.getVariateFormatId()==null){
                            throw new ParamsErrorException(HintMessage.VARIATEFORMATID_NULL);
                        }
                        String productlineCode=ruleMapper.queryProductlineCodeByOrderId(orderId);
                        ruleDetail.setRemark(cuttingOut(ruleDetail,productlineCode));
                        break;
                        default:
                        System.out.println("------------功能尚未开发---------");
                        break;
                }


            }

            staticValue=staticValue+ruleDetail.getRemark();
        }

        if(numValue==null){
            throw new ParamsErrorException(HintMessage.NUMVALUE_NULL);
        }

        //查询流水码
        RuleWatercode codeGroup = new RuleWatercode();
        codeGroup.setRuleId(ruleId);
        codeGroup.setStaticData(staticValue);
        RuleWatercode ruleWatercode = ruleWatercodeMapper.queryRuleWatercode(codeGroup);
        Integer lastNum=numValue+createNum;
        String  lastData="";
        if(ruleWatercode==null){
            //新增流水码
            lastData= String.format("%0" + numLength+ "d", lastNum );
            codeGroup.setLastData(lastData);
            ruleWatercodeMapper.insertRuleWatercode(codeGroup);
        }else{
            lastNum=Integer.valueOf(ruleWatercode.getLastData())+createNum*Integer.valueOf(numStep);
            lastData=String.format("%0" + numLength + "d", lastNum );
            ruleWatercode.setLastData( lastData);
            ruleWatercodeMapper.updateRuleWatercode(ruleWatercode);
        }
        String code="";
        List<String> list = codeList(ruleDetails, lastNum- createNum , lastNum );
//            if(cout<1){
//                throw new ParamsErrorException(HintMessage.RULE_COUNT_SMALL);
//            }
//            if(cout>1){
//                throw new ParamsErrorException(HintMessage.RULE_COUNT_BIG);
//            }
//
        return  list;

    }


        @Override
        public JSONObject createRule(Rule rule) {
        try{
            List<String> list = generateRule(rule);
            return JSONObject.oK("编号",list,list.size());
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }
    public  List<String> codeList(List<RuleDetail> ruleDetails ,Integer startDate,Integer endDate){
        List<String> list=new ArrayList<>();
        for (int i = startDate; i <endDate ; i++) {
            String code="";
        for (RuleDetail ruleDetail :ruleDetails) {

            if(ruleDetail.getRuleTypeId().equals(1)){
                code=code+  String.format("%0" + ruleDetail.getNumLength()+ "d", i );;
            }else{
                code=code+ ruleDetail.getRemark();
            }
        }
            list.add(code);
        }
        return list;
    }

    public String cuttingOut(RuleDetail ruleDetail,String str ){
        switch (ruleDetail.getVariateFormatId()) {
            case 1:
                if(ruleDetail.getEndNum()==null){
                    throw new ParamsErrorException(HintMessage.ENDNUM_NULL);
                }
                if(str.length()<ruleDetail.getEndNum()){
                    ruleDetail.setRemark(str);
                }else{
                    ruleDetail.setRemark(str.substring(0,ruleDetail.getEndNum()));
                }

                break;
            case 2:
                if(ruleDetail.getStartNum()==null){
                    throw new ParamsErrorException(HintMessage.STARTNUM_NULL);
                }
                if(str.length()<ruleDetail.getStartNum()){
                    ruleDetail.setRemark(str);
                }else {
                    ruleDetail.setRemark(str.substring(ruleDetail.getStartNum()));
                }

                break;
            case 3:
                if(ruleDetail.getEndNum()==null){
                    throw new ParamsErrorException(HintMessage.ENDNUM_NULL);

                }
                if(ruleDetail.getStartNum()==null){
                    throw new ParamsErrorException(HintMessage.STARTNUM_NULL);
                }
                if(str.length()<ruleDetail.getStartNum()){
                    ruleDetail.setRemark("");
                }else if(str.length()<ruleDetail.getEndNum()){
                    ruleDetail.setRemark(str.substring(ruleDetail.getStartNum()));
                }else{
                    ruleDetail.setRemark(str.substring(ruleDetail.getStartNum(),ruleDetail.getEndNum()));
                }


                break;
            case 4:
                ruleDetail.setRemark(str);
                break;

            default:
                ruleDetail.setRemark(str);
                break;
        }
        return ruleDetail.getRemark();
    }

    //判重
    public void checkParam(Rule rule){

        String ruleCode=rule.getRuleCode();


        //判空
        if(StringUtils.isEmpty(ruleCode)){
            throw new ParamsErrorException(HintMessage.CODE_NULL);
        }
        //判断字符长度
        if (ruleCode.getBytes().length > 100) {
            throw new ParamsErrorException(HintMessage.CODE_SIZE);
        }


        // 执行判重操作
        Integer Counts = ruleMapper.checkRule(rule);
        if (Counts !=0) {
            throw new ParamsErrorException(HintMessage.REPEATING_DATA);
        }
        Integer Count = ruleMapper.checkRuleName(rule);
        if (Count !=0) {
            throw new ParamsErrorException(HintMessage.REPEATING_DATA);
        }

    }

//    /***
//     * 新增
//     * @param rule
//     * @return
//     */
//    @Override
//    public JSONObject insertRule(Rule rule) {
//        try {
//            if(rule.getRuleId()!= null){
//                throw new ParamsErrorException("新增操作不能选择规则");
//            }
//            checkParam(rule);
//            int row = ruleMapper.insertSelective(rule);
//            if(row == 0 ){
//                throw new ParamsErrorException("新增失败");
//            }
//            return JSONObject.oK("新增成功");
//        }catch (GlobalException e){
//            logger.error(e.getMessage(), e);
//            return JSONObject.build(403, e.getMessage());
//        }
//    }
//
//    /**
//     * 删除
//     *
//     */
//    @Transactional
//    @Override
//    public JSONObject delRule(Integer[] ids, Integer dataState){
//        try {
//            if( dataState == null) {
//                throw new ParamsErrorException("数据状态不能为空");
//            }else if( dataState != 1 &&  dataState != 2 &&  dataState != 3) {
//                throw new ParamsErrorException("数据状态错误");
//            }
//            if (ids == null) {
//                throw new ParamsErrorException("请选择要删除的规则");
//            }
//            /**
//             * @author: louk
//             * @Description: 判断条码规则下是否含有条码信息
//             * @date: 2019/9/6 14:20
//             *
//             */
//            if(dataState==2){
//                int countRuleList = ruleDetailMapper.listRuleDetailByRuleId(ids);
//                if(countRuleList>0){
//                    throw new ParamsErrorException("该规则下含有条码信息无法删除");
//                }
//
//
//            }
//            // 执行存储过程
//            int row = ruleMapper.delRule(ids,dataState);
//            if(dataState==2  || row>0){
//                for(Integer id :ids){
//                    RuleDetail ruleList = new RuleDetail();
//                    ruleList.setRuleId(id);
//                    int row1 = ruleDetailMapper.delRuleDetailById(ruleList);
//                }
//            }
//            String msg = "";
//            if (row == 0) {
//                // 判断传入的数据状态参数lDataState,返回相应信息
//                switch ( dataState) {
//                    case 1:
//                        throw new ModifyFailedException("启用失败");
//                    case 2:
//                        throw new ModifyFailedException("删除失败");
//                    case 3:
//                        throw new ModifyFailedException("停用失败");
//                    default:
//                }
//            } else {
//                switch ( dataState) {
//                    case 1:
//                        msg = "启用成功";break;
//                    case 2:
//                        msg = "删除成功";break;
//                    case 3:
//                        msg = "停用成功";break;
//                    default:
//                }
//            }
//            return JSONObject.oK(msg);
//        }catch  (GlobalException e) {
//            logger.error(e.getMessage(), e);
//            return JSONObject.build(403, e.getMessage());
//        }
//    }
//
//    /**
//     * 更改
//     *
//     * @param rule
//     */
//    @Override
//    public JSONObject updateRule(Rule rule) {
//        try {
//            if(rule.getRuleId() == null) {
//                throw new ParamsErrorException("请选择要修改的规则");
//            }
//            checkParam(rule);
//
//            int	row = ruleMapper.updateByPrimaryKeySelective(rule);
//
//            if(row == 0) {
//                throw new ModifyFailedException("数据编辑失败");
//            }
//            return JSONObject.oK("编辑成功");
//        } catch (GlobalException e) {  //这里只捕获自定义异常
//            logger.error(e.getMessage(), e);
//            return JSONObject.build(403, e.getMessage());
//        }
//    }
//
//
//    /**
//     * 编码查重
//     * @param ruleId
//     * @param ruleCode
//     * @return
//     */
//    @Override
//    public Rule getByRuleCode(Integer ruleId, String ruleCode) {
//        return ruleMapper.getByRuleCode(ruleId,ruleCode);
//    }
//
//    /**
//     * 名称查重
//     * @param ruleId
//     * @param ruleName
//     * @return
//     */
//    private Rule getByRuleName(Integer ruleId, String ruleName) {
//        return ruleMapper.getByRuleName(ruleId,ruleName);
//    }
//
//    /**
//     * 查询
//     *
//     * @param rule
//     * @return
//     */
//    @Override
//    public JSONObject queryRule(Rule rule) {
//        List<Rule> liststRules = null;
//        try {
//            Integer pagesize = rule.getPagesize();
//            Integer pageindex = rule.getPageindex();
//            if(pagesize != null && pageindex != null) {
//                rule.setIncept(pagesize*(pageindex - 1));
//            }
//            Integer ruleId = rule.getRuleId();
//            if(ruleId != null) {  //如果有id,则查询单个
//                liststRules = ruleMapper.getRule(ruleId);
//            } else{  //查询多个
//                liststRules = ruleMapper.listRule(rule);
//            }
//            if (liststRules.isEmpty()){
//                return JSONObject.oK("没有相关数据", liststRules, 0);
//            }
//            //查询分页总记录数
//            int count = ruleMapper.countRule(rule);
//            return JSONObject.oK("查询成功", liststRules, count);
//
//        } catch (GlobalException e) {
//            logger.error(e.getMessage(), e);
//            return JSONObject.build(403, e.getMessage());
//        }
//    }
//
//    /**
//     * 规则校验
//     * @param rule
//     */
//    public void checkParam(Rule rule){
//        if(StringUtils.isEmpty(rule.getRuleCode())){
//            throw new ParamsErrorException("规则编码不能为空");
//        }
//        if (rule.getRuleCode().length() > 50) {
//            throw new ParamsErrorException("规则编码字数超过规定,长度50");
//        }
//        if(StringUtils.isEmpty( rule.getRuleName())){
//            throw new ParamsErrorException("规则名称不能为空");
//        }
//        if (rule.getRuleName().length() > 50) {
//            throw new ParamsErrorException("规则名称字数超过规定,长度50");
//        }
//        if(getByRuleCode(rule.getRuleId(),rule.getRuleCode()) != null){
//            throw new ParamsErrorException("规则编码已存在");
//        }
//        if(getByRuleName(rule.getRuleId(),rule.getRuleName()) != null){
//            throw new ParamsErrorException("规则名称已存在");
//        }
//    }

}
